package com.jing.juc;


import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class myLockTest{
    Lock lock = new ReentrantLock();
    public void m1(){
        if (lock.tryLock()){
            try {
                System.out.println(Thread.currentThread().getName() + "\t抢到了锁");
                TimeUnit.SECONDS.sleep(4);
                System.out.println(Thread.currentThread().getName() + "\t离开");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                lock.unlock();
            }
        } else {
            System.out.println(Thread.currentThread().getName() + "\t抢锁失败,立即离开!");
        }
    }

    public void m2(){
        try {
            if (lock.tryLock(3L, TimeUnit.SECONDS)){
                try {
                    System.out.println(Thread.currentThread().getName() + "\t抢到了锁");
                    TimeUnit.SECONDS.sleep(2);
                    System.out.println(Thread.currentThread().getName() + "\t离开");
                } finally {
                    lock.unlock();
                }
            } else {
                System.out.println(Thread.currentThread().getName() + "\t抢锁失败,超时!");
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
public class LockTest {
    public static void main(String[] args) {
        myLockTest myLockTest = new myLockTest();
//        new Thread(() -> myLockTest.m1(),"A").start();
//        new Thread(() -> myLockTest.m1(),"B").start();
        new Thread(() -> myLockTest.m2(),"C").start();
        new Thread(() -> myLockTest.m2(),"D").start();
    }
}
